﻿namespace BEGDC.CC.Web.UserControls.EV
{
    using System;
    using System.Collections;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using BEGDC.CC.BL.CCFlow.CR;
    using BEGDC.CC.BL.CCFlow.EV;
    using BEGDC.CC.BL.Common;
    using BEGDC.CC.BL.Common.Query;
    using BEGDC.CC.BL.UserManagement;
    using BEGDC.CC.BL.Workflow;
    using BEGDC.CC.Entity;
    using BEGDC.Utility.Castle;


    /// <summary>
    ///		Summary description for EVApplication.
    /// </summary>
    public class EVApplication : BaseEV
    {
        //Other Account
        private const string OtherAccounts = "Others";
        protected System.Web.UI.WebControls.TextBox tbOtherAccount;
        protected System.Web.UI.WebControls.CheckBoxList CBL_ASBLeader;
        protected System.Web.UI.WebControls.DataGrid dgASBLeaders;
        protected System.Web.UI.HtmlControls.HtmlTableRow trCheckBoxASBLeader;
        protected System.Web.UI.HtmlControls.HtmlTableRow trDataGridASBLeader;

        protected System.Web.UI.WebControls.Button btnProposedExecutives;
        //protected System.Web.UI.WebControls.DropDownList dropProposedTimeList;
        //protected System.Web.UI.WebControls.Label lblCluster;
        protected System.Web.UI.WebControls.TextBox lblCluster;
        //protected Color color;

        protected BEGDC.CC.Web.UserControls.Export ctrlExport;
        protected System.Web.UI.WebControls.TextBox txtProposedDate;
        protected System.Web.UI.WebControls.TextBox txtOptionalDate;
        // protected System.Web.UI.WebControls.TextBox txtProposedTime;
        //protected System.Web.UI.WebControls.TextBox txtOptionalTime;
        protected System.Web.UI.WebControls.Button ibtnSave;
        protected System.Web.UI.WebControls.Button ibtnSubmit;
        protected System.Web.UI.WebControls.Button ibtnCopy;
        protected System.Web.UI.WebControls.Button ibtnReply;

        protected System.Web.UI.WebControls.TextBox txtCompany;
        protected System.Web.UI.WebControls.TextBox txtVenue;
        protected System.Web.UI.WebControls.TextBox txtVisitingPurpose;
        protected System.Web.UI.WebControls.CheckBoxList chkListActivities;
        protected System.Web.UI.HtmlControls.HtmlInputHidden txtDirectorName;
        protected System.Web.UI.WebControls.TextBox tbOperationFlag;
        protected System.Web.UI.WebControls.Label lblDept;
        protected System.Web.UI.WebControls.DropDownList ddlCATBranch;
        //protected System.Web.UI.WebControls.Label lblAccount;
        protected System.Web.UI.WebControls.DropDownList ddlAccount;
        protected System.Web.UI.WebControls.Label lblDeptValue;
        protected System.Web.UI.WebControls.Label lblCATBranchValue;
        protected System.Web.UI.WebControls.Label lblAccountValue;
        protected System.Web.UI.WebControls.Label lblProDateValue;
        //protected System.Web.UI.WebControls.Label lblProTimeValue;
        //protected System.Web.UI.WebControls.Label lblOptTimeValue;
        protected System.Web.UI.WebControls.Label lblCompanyValue;
        protected System.Web.UI.WebControls.Label lblVenueValue;
        protected System.Web.UI.WebControls.Label lblActivityValue;
        //protected System.Web.UI.WebControls.Label lblApplicantValue;
        protected System.Web.UI.WebControls.Label lblOptDateValue;
        protected System.Web.UI.WebControls.TextBox tbOperationContent;
        protected System.Web.UI.WebControls.DataGrid dtGridProExecutives;
        protected System.Web.UI.WebControls.Button imgAddAttendee;
        protected System.Web.UI.HtmlControls.HtmlGenericControl proposedDate;
        protected System.Web.UI.HtmlControls.HtmlGenericControl optionalDate;
        protected System.Web.UI.WebControls.TextBox txtCustomerID;
        protected System.Web.UI.WebControls.DataGrid dgCustomerList;
        protected System.Web.UI.WebControls.Button CustomerPaneImg;
        protected System.Web.UI.WebControls.Label Lb_CISWarning;
        protected System.Web.UI.WebControls.Label lbAppNo;
        protected System.Web.UI.HtmlControls.HtmlTableRow tr_Title;
        protected System.Web.UI.HtmlControls.HtmlTableRow tr_TitleAlt;
        protected System.Web.UI.HtmlControls.HtmlGenericControl dv_TitleAlt;
        protected System.Web.UI.WebControls.DropDownList ddlLegalEntity;
        protected System.Web.UI.WebControls.Label lblLegalEntity;
        //protected System.Web.UI.HtmlControls.HtmlTable tbKnowledgeSharing;
        //protected System.Web.UI.HtmlControls.HtmlTableCell tdSummary;
        protected System.Web.UI.HtmlControls.HtmlTableCell tdVisitingPur;
        protected ASB.CC.Web.UserControls.RequesterInfoControl RequesterInfoControl;
        protected System.Web.UI.HtmlControls.HtmlInputHidden positionflag;
        #region Property

        private int FlowID
        {
            get
            {
                if (Request.QueryString["flowid"] + string.Empty == string.Empty)
                {
                    return 0;
                }
                else
                {
                    return Convert.ToInt32(Request.QueryString["flowid"]);
                }
            }
        }
        private int CustInfoID
        {
            get
            {
                if (ViewState["CustInfoID"] == null)
                    return 0;
                else
                    return Convert.ToInt32(ViewState["CustInfoID"]);
            }
            set
            {
                ViewState["CustInfoID"] = value;
            }
        }
        private CustomerInfo CustInfo
        {
            get
            {
                if (Session[CustInfoID + "CustInfo"] == null)
                    return null;
                else
                    return (CustomerInfo)Session[CustInfoID + "CustInfo"];
            }
            set
            {
                Session[CustInfoID + "CustInfo"] = value;
            }
        }

        private bool IsQuery
        {
            get
            {
                string state = this.Request.QueryString["State"];
                if (state == null) return false;
                return state == SysDicItem.ProjectStatusFlag.QUERY;
            }
        }
        private bool IsView
        {
            get
            {
                string state = this.Request.QueryString["State"];
                if (state == null) return false;
                if (state == SysDicItem.ProjectStatusFlag.View || state == SysDicItem.ProjectStatusFlag.CANCEL
                    || state == SysDicItem.ProjectStatusFlag.Pending || state == SysDicItem.ProjectStatusFlag.End
                    || state == SysDicItem.ProjectStatusFlag.Participation)
                    return true;
                else
                    return false;
            }
        }

        protected string Dept
        {
            get
            {
                if (this.ddlCATBranch.Visible)
                    return this.ddlCATBranch.SelectedItem.Text;
                else
                    return this.lblCATBranchValue.Text;
            }
        }


        private object AlAttendee
        {
            get
            {
                return Session[SessionFlag.AccompanySessionEZ];
            }
            set
            {
                Session[SessionFlag.AccompanySessionEZ] = value;
            }
        }

        protected string Step
        {
            get
            {
                IQuery queryService = BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.QueryService] as IQuery;
                FlowInstance flowInstance = queryService.QueryFlowInstance(this.AppID);
                if (flowInstance == null)
                    return WorkTransition.Draft;
                else
                    return flowInstance.CurrentActiveStep.StepCode;
            }
        }

        #endregion

        private void Page_Load(object sender, System.EventArgs e)
        {
            // Put user code to initialize the page here
            if (!Page.IsPostBack)
            {
                Session[SessionFlag.AccompanySessionEZ] = null;
                Session[SessionFlag.CustomerSessionEZ] = null;
                Session[SessionFlag.ContractInfo] = null;
                Session[SessionFlag.CostCenter] = null;
                Session[SessionFlag.AccompanySession] = null;
                Session[SessionFlag.CustomerSession] = null;
                Session[SessionFlag.MeetingMinutesAttendee] = null;

                base.InitCommonData();
                this.AlAttendee = null;
                this.CustInfo = null;
                this.CustInfoID = 0;
                //Session[SessionFlag.CustomerSessionEZ] = null;		

                if (this.Application != null && this.Application.AppNo != string.Empty)
                    this.lbAppNo.Text = " Application No:" + this.Application.AppNo;

                ControlStatusSetting();

                //Show textbox or label
                if (this.Access != null)
                    ControlVisibleSetting(((EVAccessControl)Access).IsReadOnlyForApp);


                this.ibtnSubmit.Attributes["onclick"] = "javascript:OnSubmit();";
                this.ibtnReply.Attributes.Add("onclick", "javascript:OpenReplyPane(" + Request.QueryString["flowid"] + ")");
                this.CustomerPaneImg.Attributes.Add("onclick", "javascript:OpenCustomerPane(0)");
                this.imgAddAttendee.Attributes.Add("onclick", "javascript:OpenALAttendeePane(0)");
                //ShowKnowledgeSharing();

                //positionflag
                if (!string.IsNullOrEmpty(Request.QueryString["pf"]))
                {
                    int position;
                    if (Int32.TryParse(Request.QueryString["pf"], out position))
                        positionflag.Value = position.ToString();
                }
            }

            this.RequesterInfoControl.isReadOnly = ((EVAccessControl)Access).IsReadOnlyForApp;
            BindCustomerAttendee();
            BindALAttendee();
            BindASBLeaders();
        }

        protected override void OnPreRender(EventArgs e)
        {
            tr_TitleAlt.Visible = !tr_Title.Visible;
            dv_TitleAlt.Visible = !tr_Title.Visible;

            base.OnPreRender(e);
        }

        protected override void ButtonStatusSetting()
        {
            if (this.Access == null)
                return;
            if (Access.IsHideAllButton)
            {
                this.ibtnReply.Visible = false;
                this.ibtnSave.Visible = false;
                this.ibtnCopy.Visible = false;
                this.ibtnSubmit.Visible = false;
                this.imgAddAttendee.Visible = false;
                this.dgCustomerList.Columns[8].Visible = false;
                this.dtGridProExecutives.Columns[3].Visible = false;
                this.trCheckBoxASBLeader.Visible = false;
                this.trDataGridASBLeader.Visible = true;
                //this.CBL_ASBLeader.Enabled = false;
                //this.btnProposedExecutives.Visible = false;
                this.tr_Title.Visible = false;
            }
            else if (Access.IsQuery)
            {
                this.ibtnReply.Visible = true;
                this.ibtnSave.Visible = true;

                this.ibtnCopy.Visible = false;
                this.ibtnSubmit.Visible = false;

                //this.imgAddAttendee.Visible = false;
                //this.dgCustomerList.Columns[6].Visible = false;
                //this.dtGridProExecutives.Columns[3].Visible = false;

                //CAT Branch and Accout should not be changed
                this.ddlCATBranch.Enabled = false;
                this.tbOtherAccount.Enabled = false;
            }
            else
            {
                this.ibtnSave.Visible = true;
                if (this.AppID > 0)
                {
                    this.ibtnCopy.Visible = true;
                }
                else
                {
                    this.ibtnCopy.Visible = false;
                }
                this.ibtnReply.Visible = false;
                this.ibtnSubmit.Visible = Access.IsButtonVisible(EVTransitionList.Submit);
            }

        }

        protected override void ControlStatusSetting()
        {
            ButtonStatusSetting();
        }

        public void ShowModifyStatus()
        {
            this.imgAddAttendee.Visible = true;
            this.CustomerPaneImg.Visible = true;
            this.proposedDate.Visible = true;
            this.optionalDate.Visible = true;
            this.txtProposedDate.Visible = true;
            this.txtProposedDate.Text = this.lblProDateValue.Text;
            this.txtOptionalDate.Visible = true;
            this.txtOptionalDate.Text = this.lblOptDateValue.Text;

            this.lblProDateValue.Visible = false;
            this.lblOptDateValue.Visible = false;
        }

        public void EndModifyStatus()
        {
            this.imgAddAttendee.Visible = false;
            this.CustomerPaneImg.Visible = false;
            this.proposedDate.Visible = false;
            this.optionalDate.Visible = false;

            this.txtProposedDate.Visible = false;
            this.txtOptionalDate.Visible = false;
            //<--joan 2007/8/20
            // this.txtProposedTime.Visible = false;
            //this.dropProposedTimeList.Visible = false;

            //this.txtOptionalTime.Visible = false;

            this.lblProDateValue.Visible = true;
            //this.lblProTimeValue.Visible = true;
            if (Application.RequestedDateFrom != Nullables.NullableDateTime.Default)
            {
                this.lblProDateValue.Text = WebUtility.FormatDateString(Application.RequestedDateFrom.Value);
                //this.lblProTimeValue.Text = Application.RequestedDateFrom.Value.ToString("HH:mm");
            }
            else
            {
                this.lblProDateValue.Text = "";
                //this.lblProTimeValue.Text = "";
            }


            //this.lblOptTimeValue.Visible = true;


            this.lblOptDateValue.Visible = true;
            if (Application.AlternateDateFrom != Nullables.NullableDateTime.Default)
            {
                this.lblOptDateValue.Text = WebUtility.FormatDateString(Application.AlternateDateFrom.Value);
                // this.lblOptTimeValue.Text = Application.AlternateDateFrom.Value.ToString("HH:mm");
            }
            else
            {
                this.lblOptDateValue.Text = "";
                //this.lblOptTimeValue.Text = "";
            }
            //-->end


        }


        //this Save is unuseful
        public void Save()
        {
            IEV EVService = AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.EVService] as IEV;
            Modify2Save();
            System.Collections.IList list = new System.Collections.ArrayList();
            this.BuildALAttendee(ref list);

            IList custAttendeeList = new ArrayList();
            BuildCustomerAttendee(ref custAttendeeList);

            EVService.SaveEVRequest(this.Application, this.CustInfo, list, custAttendeeList, null);
        }

        /// <summary>
        /// isQuery==true, show lables, or show textboxes;
        /// </summary>
        /// <param name="isQuery"></param>
        private void ControlVisibleSetting(bool isReadonly)
        {
            if (isReadonly)
            {

                #region Set TextBox invisible
                this.txtCompany.Visible = false;
                this.txtDirectorName.Visible = false;
                this.txtOptionalDate.Visible = false;
                //this.txtOptionalTime.Visible = false;
                this.txtProposedDate.Visible = false;
                //this.txtProposedTime.Visible = false;
                //this.dropProposedTimeList.Visible = false;

                this.txtVenue.Visible = false;
                this.txtVisitingPurpose.Visible = false;
                this.ddlAccount.Visible = false;
                this.chkListActivities.Visible = false;
                this.ddlCATBranch.Visible = false;
                this.ddlLegalEntity.Visible = false;
                this.proposedDate.Visible = false;
                this.optionalDate.Visible = false;

                #endregion

                #region Set Application Infomation
                if (this.Application != null)
                {
                    //this.lblApplicantValue.Text = Application.RequesterNameEN;
                    this.lblAccountValue.Text = Application.Account;
                    this.lblDeptValue.Text = Application.RequesterDept;
                    if (Application.LegalEntity != null)
                        this.lblLegalEntity.Text = Application.LegalEntity.LegalEntityName;
                    //if (this.Application.DepartmentName != null)
                    //    this.lblCATBranchValue.Text = Application.DepartmentName.DepartmentCode;
                    if (this.Application.CATBranch != null)
                    {
                        this.lblCATBranchValue.Text = Application.CATBranch;
                        this.lblCluster.Text = Application.Others;
                    }
                    if (Application.DepartmentType.DicItemKey == "CAT")
                    {
                        this.lblAccountValue.Visible = false;
                        // this.lblAccount.Visible = false;
                    }

                    if (Application.RequestedDateFrom != Nullables.NullableDateTime.Default)
                    {
                        this.lblProDateValue.Text = WebUtility.FormatDateString(Application.RequestedDateFrom.Value);
                        //this.lblProTimeValue.Text = Application.RequestedDateFrom.Value.ToString("HH:mm");
                        //if (this.lblProTimeValue.Text == "00:00")
                        //    this.lblProTimeValue.Text = "";

                    }
                    if (Application.AlternateDateFrom != Nullables.NullableDateTime.Default)
                    {
                        this.lblOptDateValue.Text = WebUtility.FormatDateString(Application.AlternateDateFrom.Value);
                        //this.lblOptTimeValue.Text = Application.AlternateDateFrom.Value.ToString("HH:mm");
                        //if (this.lblOptTimeValue.Text == "00:00")
                        // this.lblOptTimeValue.Text = "";
                    }
                    this.lblActivityValue.Text = Application.Activity;
                }
                else
                {
                    this.ibtnCopy.Visible = false;
                }
                BEGDC.CC.BL.Common.Query.IQuery queryService = AppContainer.Instance[ServiceConst.QueryService] as BEGDC.CC.BL.Common.Query.IQuery;
                CustomerInfo custInfo = queryService.GetCustomerInfo(this.AppID);
                if (custInfo != null)
                {
                    this.CustInfoID = custInfo.Id;
                    this.CustInfo = custInfo;
                }
                if (this.CustInfo != null)
                {
                    this.lblCompanyValue.Text = CustInfo.Company;
                    this.lblVenueValue.Text = CustInfo.Venue;
                    if (CustInfo.VisitObjective + string.Empty != string.Empty)
                        this.tdVisitingPur.InnerHtml = CustInfo.VisitObjective.Replace("\r\n", "<br>");
                }
                #endregion

                //Hide add button
                this.imgAddAttendee.Visible = false;
                this.CustomerPaneImg.Visible = false;

                //Hide Action Column
                this.dgCustomerList.Columns[6].Visible = false;
                this.dtGridProExecutives.Columns[3].Visible = false;
                this.trCheckBoxASBLeader.Visible = false;
                this.trDataGridASBLeader.Visible = true;
                //this.CBL_ASBLeader.Enabled = false;
                //this.btnProposedExecutives.Visible = false;
            }
            else
            {
                this.lblAccountValue.Visible = false;
                this.lblActivityValue.Visible = false;
                this.lblCATBranchValue.Visible = false;
                this.lblActivityValue.Visible = false;
                this.lblCompanyValue.Visible = false;
                this.lblOptDateValue.Visible = false;
                // this.lblOptTimeValue.Visible = false;
                this.lblProDateValue.Visible = false;
                //this.lblProTimeValue.Visible = false;
                this.lblVenueValue.Visible = false;
                this.lblLegalEntity.Visible = false;

                //Set Application Infomation
                InitAccountInfo();
                InitAppInfo();
            }


        }

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        ///		Required method for Designer support - do not modify
        ///		the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.ibtnSave.Click += new EventHandler(ibtnSave_Click);
            this.ibtnReply.Click += new EventHandler(ibtnReply_Click);
            this.ibtnSubmit.Click += new EventHandler(ibtnSubmit_Click);
            this.ibtnCopy.Click += new EventHandler(ibtnCopy_Click);
            this.ddlCATBranch.SelectedIndexChanged += new System.EventHandler(this.ddlCATBranch_SelectedIndexChanged);
            this.dgCustomerList.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dgCustomerList_ItemCommand);
            this.dgCustomerList.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dgCustomerList_ItemDataBound);
            this.dtGridProExecutives.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dtGridProExecutives_ItemCommand);
            this.dtGridProExecutives.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dtGridProExecutives_ItemDataBound);

            // this.color = this.ddlCATBranch.ControlStyle.BackColor;

            this.Load += new System.EventHandler(this.Page_Load);
        }

        #endregion

        /// <summary>
        /// init account information
        /// </summary>
        private void InitAccountInfo()
        {
            if (Application == null)
            {
                string nameEN = HttpContext.Current.User.Identity.Name;
                //this.lblApplicantValue.Text = nameEN;
                IUser userService = AppContainer.Instance[ServiceConst.UserService] as IUser;
                Employee emp = userService.GetUserByEnglishName(nameEN);
                if (emp != null && emp.Department != null)
                    this.lblDeptValue.Text = emp.Department.DepartmentCode;
            }
            else
            {
                if (Application.RequesterNo != null)
                {
                    //this.lblApplicantValue.Text = Application.RequesterNo.NameEN;
                    this.lblDeptValue.Text = Application.RequesterDept;

                }
            }
        }

        /// <summary>
        /// 初始化当前Applicant
        /// </summary>
        private void InitAppInfo()
        {
            try
            {
                #region Init Dropdown list
                BEGDC.CC.BL.Common.Query.IQuery queryService = AppContainer.Instance[ServiceConst.QueryService] as BEGDC.CC.BL.Common.Query.IQuery;

                //init account
                DataTable accountTable = queryService.GetDicItemByTypeName(BEGDC.CC.BL.Common.DicType.ACCOUNT);
                this.ddlAccount.DataSource = accountTable.DefaultView;
                this.ddlAccount.DataValueField = "DicItemKey";
                this.ddlAccount.DataTextField = "Description";
                this.ddlAccount.DataBind();
                this.ddlAccount.Items.Insert(0, new ListItem("Please select", String.Empty));

                //init legal entity
                this.ddlLegalEntity.DataSource = queryService.GetAllLegalEntity();
                this.ddlLegalEntity.DataTextField = "LegalEntityName";
                this.ddlLegalEntity.DataValueField = "LegalEntityID";
                this.ddlLegalEntity.DataBind();

                //init cat branch
                DataTable categoryTable = queryService.GetPCATNameList(true);
                DataTable provinceTable = queryService.GetPCATNameList(false);
                foreach (DataRow row in categoryTable.Select())
                {
                    provinceTable.ImportRow(row);
                }

                this.ddlCATBranch.DataSource = provinceTable.DefaultView;
                this.ddlCATBranch.DataTextField = "Name";
                this.ddlCATBranch.DataValueField = "Name";
                this.ddlCATBranch.DataBind();
                this.ddlCATBranch.Items.Insert(0, new ListItem("Please select", String.Empty));

                this.chkListActivities.DataSource = queryService.GetDicItemByTypeName(BEGDC.CC.BL.Common.DicType.ACTIVITY);
                this.chkListActivities.DataTextField = "DicItemKey";
                this.chkListActivities.DataBind();

                ////init Proposed Time
                //if (dropProposedTimeList.Items.Count < 1)
                //{
                //    for (int proposedTimeStar = 9; proposedTimeStar < 21; proposedTimeStar++)
                //    {
                //        this.dropProposedTimeList.Items.Add(new ListItem(proposedTimeStar.ToString("00") + ":00"));
                //        this.dropProposedTimeList.Items.Add(new ListItem(proposedTimeStar.ToString("00") + ":30"));
                //    }
                //    this.dropProposedTimeList.Items.Insert(0, new ListItem("Please Select", String.Empty));
                //}
                #endregion

                #region Init Application Information
                if (this.Application != null)
                {
                    if (Application.RequestedDateFrom != Nullables.NullableDateTime.Default)
                    {
                        //string nullProposedDateStr = WebUtility.FormatDateString(new DateTime(1990, 1, 1));
                        //this.txtProposedDate.Text = WebUtility.FormatDateString(Application.RequestedDateFrom.Value) == nullProposedDateStr ? "" : WebUtility.FormatDateString(Application.RequestedDateFrom.Value);
                        //var item = this.dropProposedTimeList.Items.FindByText(Application.RequestedDateFrom.Value.ToString("HH:mm"));
                        //if (item != null)
                        //    item.Selected = true;
                        this.txtProposedDate.Text = WebUtility.FormatDateString(Application.RequestedDateFrom.Value);
                    }
                    if (Application.AlternateDateFrom != Nullables.NullableDateTime.Default)
                    {
                        this.txtOptionalDate.Text = WebUtility.FormatDateString(Application.AlternateDateFrom.Value);
                    }

                    this.ddlCATBranch.Text = Application.CATBranch.ToString();
                    this.lblCluster.Text = Application.Others;
                    //this.lblCluster.CssClass = "Cluster_Block";

                    if (string.IsNullOrEmpty(this.ddlCATBranch.SelectedValue))
                    {
                        this.lblCluster.Text = string.Empty;
                    }

                    if (Application.DepartmentName != null)
                    {
                        //this.ddlCATBranch.SelectedValue = Application.DepartmentName.DepartmentCode.ToString();
                        if (Application.DepartmentType.DicItemKey == "CAT")
                        {
                            this.ddlAccount.Visible = false;
                        }
                    }
                    if (Application.LegalEntity != null)
                    {
                        this.ddlLegalEntity.SelectedValue = Application.LegalEntity.Id.ToString();
                    }
                    //Other Account
                    //this.ddlAccount.SelectedValue = Application.Account;
                    if (this.ddlAccount.Items.FindByValue(this.Application.Account) != null)
                    {
                        this.ddlAccount.SelectedValue = Application.Account;
                    }
                    else
                    {
                        this.ddlAccount.SelectedValue = OtherAccounts;
                        this.tbOtherAccount.Text = Application.Account;
                    }

                    this.SelectActivites(Application.Activity);
                }

                #endregion

                #region Init CustomerInfo
                CustomerInfo custInfo = queryService.GetCustomerInfo(this.AppID);
                if (custInfo != null)
                {
                    this.CustInfoID = custInfo.Id;
                    this.CustInfo = custInfo;
                }
                if (this.CustInfo != null)
                {
                    this.txtCompany.Text = CustInfo.Company;
                    this.txtVenue.Text = CustInfo.Venue;
                    this.txtVisitingPurpose.Text = CustInfo.VisitObjective;
                }
                #endregion

            }
            catch (BEGDC.Utility.ExceptionManagement.GDCException gdcEx)
            {
                //todo
            }
        }

        private void BindALAttendee()
        {
            DataTable AccompanyingAttendee = null;
            if (AlAttendee != null)
            {
                AccompanyingAttendee = (DataTable)AlAttendee;
            }
            else
            {
                if (this.AppID > 0)
                {
                    ICR crService = AppContainer.Instance[ServiceConst.CRService] as ICR;
                    AccompanyingAttendee = crService.GetAccompanyingAttendeeList(this.AppID);
                }
                if (AccompanyingAttendee == null || AccompanyingAttendee.Rows.Count == 0)
                {
                    AccompanyingAttendee = new DataTable();
                    AccompanyingAttendee.Columns.Add(new DataColumn("Id", typeof(System.String)));
                    AccompanyingAttendee.Columns.Add(new DataColumn("EmployeeId", typeof(System.String)));
                    AccompanyingAttendee.Columns.Add(new DataColumn("Name", typeof(System.String)));
                    AccompanyingAttendee.Columns.Add(new DataColumn("Title", typeof(System.String)));
                }
                AlAttendee = AccompanyingAttendee;
            }
            this.dtGridProExecutives.DataSource = this.SetRowID(AccompanyingAttendee);
            this.dtGridProExecutives.DataBind();
        }


        //private void ShowKnowledgeSharing()
        //{
        //    this.tbKnowledgeSharing.Visible = false;

        //    string strFlowId = Request.QueryString["flowId"];
        //    if (strFlowId + string.Empty != string.Empty)
        //    {
        //        int flowId = Convert.ToInt32(strFlowId);
        //        IQuery queryService = AppContainer.Instance[ServiceConst.QueryService] as IQuery;
        //        FlowInstance instance = queryService.QueryFlowInstanceByFlowId(flowId);
        //        if (instance.CurrentStep.StepCode == WorkTransition.EV_End)
        //        {
        //            this.tbKnowledgeSharing.Visible = true;
        //            if (Application.Summary + string.Empty != string.Empty)
        //                this.tdSummary.InnerHtml = Application.Summary.Replace("\r\n", "<br>");
        //        }
        //    }
        //}

        private DataTable SetRowID(DataTable table)
        {
            if (table != null && table.Rows.Count > 0)
                for (int i = 1; i <= table.Rows.Count; i++)
                {
                    table.Rows[i - 1][0] = i.ToString();
                }
            return table;
        }

        private void SelectActivites(string activies)
        {
            if (activies + string.Empty == string.Empty)
            {
                return;
            }
            string[] activity = activies.Split(';');
            for (int i = 0; i < activity.Length; i++)
            {
                foreach (ListItem li in this.chkListActivities.Items)
                {
                    if (li.Text == activity[i])
                    {
                        li.Selected = true;
                        break;
                    }
                }
            }
        }


        //this Modify2Save is unuseful***********
        private void Modify2Save()
        {
            if (this.txtProposedDate.Text != string.Empty)
            {
                //string requestedDate = this.txtProposedDate.Text + " " + this.dropProposedTimeList.SelectedValue;

                Application.RequestedDateFrom = new Nullables.NullableDateTime(Convert.ToDateTime(this.txtProposedDate.Text));
                Application.RequestedDateTo = Application.RequestedDateFrom;
            }
            else
            {
                Application.RequestedDateFrom = Nullables.NullableDateTime.Default;
                Application.RequestedDateTo = Application.RequestedDateFrom;

                //if (!string.IsNullOrEmpty(this.dropProposedTimeList.SelectedValue))
                //{
                //    string nullProposedDateStr = WebUtility.FormatDateString(new DateTime(1990, 1, 1));
                //    string requestedDate = nullProposedDateStr + " " + this.dropProposedTimeList.SelectedValue;
                //    Application.RequestedDateFrom = new Nullables.NullableDateTime(Convert.ToDateTime(requestedDate));
                //    //Application.RequestedDateTo = Application.RequestedDateFrom;
                //}
                //else
                //{
                //    Application.RequestedDateFrom = Nullables.NullableDateTime.Default;
                //    Application.RequestedDateTo = Application.RequestedDateFrom;
                //}
            }
            if (this.txtOptionalDate.Text != string.Empty)
            {
                string optionalDate = this.txtOptionalDate.Text;
                Application.AlternateDateFrom = new Nullables.NullableDateTime(Convert.ToDateTime(optionalDate));
            }
            else
            {
                Application.AlternateDateFrom = Nullables.NullableDateTime.Default;
                Application.AlternateDateTo = Application.AlternateDateFrom;
            }
        }

        private bool BuildApp2Save()
        {
            if (base.Application == null)
            {
                Application = new Application();
            }

            Application.ApplyForSomeoneElse = false;
            Application.IsReviewedGuideline = false;
            Application.RequesterNameEN = HttpContext.Current.User.Identity.Name;
            //Application.RequesterMobile = this.RequesterInfoControl.Employee.Mobile;
            //Application.RequesterOfficeTel = this.RequesterInfoControl.Employee.OfficePhone;
            Application.RequesterMobile = this.RequesterInfoControl.Mobile;
            Application.RequesterOfficeTel = this.RequesterInfoControl.OfficePhone;
            //Other Account
            //Application.Account = this.ddlAccount.SelectedValue;
            if (this.ddlAccount.SelectedValue == "" && this.ddlAccount.Visible)
            {
                Page.RegisterClientScriptBlock("", "<script>alert('Account could not be empty. 大客户不能为空!');</script>");
                return false;
            }
            if (this.ddlAccount.SelectedValue == OtherAccounts && string.IsNullOrEmpty(this.tbOtherAccount.Text.Trim()))
            {
                Page.RegisterClientScriptBlock("", "<script>alert('Other Account could not be empty. 其他大客户不能为空! ');</script>");
                return false;
            }

            Application.Account = (this.ddlAccount.SelectedValue == OtherAccounts) ? this.tbOtherAccount.Text.Trim() : this.ddlAccount.SelectedValue;

            Application.RequesterDept = this.lblDeptValue.Text;
            Application.LegalEntity = new LegalEntity();
            Application.LegalEntity.Id = Convert.ToInt32(this.ddlLegalEntity.SelectedValue);

            IQuery query = AppContainer.Instance[ServiceConst.QueryService] as IQuery;

            //save selected PCAT
            Application.CATBranch = this.ddlCATBranch.SelectedValue.ToString();
            //Save cluster of the selected Province
            Application.Others = query.GetClusterByProvinceName(Application.CATBranch);


            if (!string.IsNullOrEmpty(Application.Others))
            {
                Application.DepartmentName = query.GetDepartmentByPCAT(this.ddlCATBranch.SelectedValue, true);
            }
            else
            {
                Application.DepartmentName = query.GetDepartmentByPCAT(this.ddlCATBranch.SelectedValue, false);
            }

            if (Application.DepartmentName == null)
            {
                Page.RegisterClientScriptBlock("", "<script>alert('No department in the PCAT. 该省份或大客户没有对应的部门!');</script>");
                return false;
            }

            Application.DepartmentType = Application.DepartmentName.DepartmentType;

            Application.ApplicationType = BEGDC.CC.BL.Workflow.WorkflowTypes.EV;
            if (this.txtProposedDate.Text != string.Empty)
            {
                //string requestedDate = this.txtProposedDate.Text + " " + this.dropProposedTimeList.SelectedValue;

                //Application.RequestedDateFrom = new Nullables.NullableDateTime(Convert.ToDateTime(requestedDate));
                //Application.RequestedDateTo = Application.RequestedDateFrom;

                Application.RequestedDateFrom = new Nullables.NullableDateTime(Convert.ToDateTime(this.txtProposedDate.Text));
                Application.RequestedDateTo = Application.RequestedDateFrom;
            }
            else
            {
                Application.RequestedDateFrom = Nullables.NullableDateTime.Default;
                Application.RequestedDateTo = Application.RequestedDateFrom;
                //if (!string.IsNullOrEmpty(this.dropProposedTimeList.SelectedValue))
                //{
                //    string nullProposedDateStr = WebUtility.FormatDateString(new DateTime(1990, 1, 1));
                //    string requestedDate = nullProposedDateStr + " " + this.dropProposedTimeList.SelectedValue;
                //    Application.RequestedDateFrom = new Nullables.NullableDateTime(Convert.ToDateTime(requestedDate));
                //    //Application.RequestedDateTo = Application.RequestedDateFrom;
                //}
                //else
                //{
                //    Application.RequestedDateFrom = Nullables.NullableDateTime.Default;
                //    Application.RequestedDateTo = Application.RequestedDateFrom;
                //}
            }

            if (this.txtOptionalDate.Text != string.Empty)
            {
                string optionalDate = this.txtOptionalDate.Text;
                Application.AlternateDateFrom = new Nullables.NullableDateTime(Convert.ToDateTime(optionalDate));

            }
            Application.Activity = BuildSelectedActivies();

            //build CustomerInfo object
            if (this.CustInfo == null)
            {
                CustInfo = new CustomerInfo();
            }
            CustInfo.Application = this.Application;
            CustInfo.Company = txtCompany.Text;
            CustInfo.Venue = txtVenue.Text;
            CustInfo.VisitObjective = txtVisitingPurpose.Text;
            return true;
        }

        private void BuildALAttendee(ref System.Collections.IList attendeeList)
        {
            // AL Attendee Info
            if (this.AlAttendee == null)
                return;

            DataTable table = (DataTable)this.AlAttendee;
            if (table != null && table.Rows.Count > 0)
            {
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    ALAttendee al = new ALAttendee();
                    al.EmployeeId = new Employee();
                    al.EmployeeId.Id = table.Rows[i]["EmployeeId"].ToString();
                    al.Title = table.Rows[i]["Title"].ToString();
                    attendeeList.Add(al);
                }
            }
        }

        private void BuildCustomerAttendee(ref IList custAttendeeList)
        {
            DataTable table = (DataTable)this.dgCustomerList.DataSource;
            if (table != null && table.Rows.Count > 0)
            {
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    CustomerAttendee cus = new CustomerAttendee();
                    cus.NameEN = table.Rows[i]["Name"].ToString();
                    cus.Title = table.Rows[i]["Title"].ToString();
                    cus.Company = table.Rows[i]["Company"].ToString();
                    cus.NameCN = table.Rows[i]["NameCN"].ToString();
                    cus.TitleEN = table.Rows[i]["TitleEN"].ToString();
                    cus.CompanyEN = table.Rows[i]["CompanyEN"].ToString();

                    cus.Responsibility = new DicItem();
                    cus.Responsibility.Id = Convert.ToInt32(table.Rows[i]["ResponsibilityID"]);
                    cus.Affects = new DicItem();
                    cus.Affects.Id = Convert.ToInt32(table.Rows[i]["AffectsID"]);

                    cus.IsAttended = true;
                    cus.IsExisted = Convert.ToInt32(table.Rows[i]["IsExisted"]);
                    cus.Remark = table.Rows[i]["Remark"].ToString();

                    custAttendeeList.Add(cus);
                }
            }
        }

        private void BindCustomerAttendee()
        {
            DataTable CustomerDataTable = null;
            object SessCustomerAttendee = Session[SessionFlag.CustomerSessionEZ];
            if (SessCustomerAttendee != null)
            {
                CustomerDataTable = (DataTable)SessCustomerAttendee;
            }
            else
            {
                if (this.CustInfoID > 0)
                {
                    IQuery queryService = AppContainer.Instance[ServiceConst.QueryService] as IQuery;
                    CustomerDataTable = queryService.GetCustomerAttendeeList(this.CustInfoID);
                }
                if (CustomerDataTable != null && CustomerDataTable.Rows.Count > 0)
                {
                    Session[SessionFlag.CustomerSessionEZ] = CustomerDataTable;
                }
                else
                {
                    CustomerDataTable = new DataTable();
                    CustomerDataTable.Columns.Add(new DataColumn("Id", typeof(System.String)));
                    CustomerDataTable.Columns.Add(new DataColumn("Name", typeof(System.String)));
                    CustomerDataTable.Columns.Add(new DataColumn("NameCN", typeof(System.String)));
                    CustomerDataTable.Columns.Add(new DataColumn("CompanyEN", typeof(System.String)));
                    CustomerDataTable.Columns.Add(new DataColumn("Company", typeof(System.String)));
                    CustomerDataTable.Columns.Add(new DataColumn("Title", typeof(System.String)));
                    CustomerDataTable.Columns.Add(new DataColumn("TitleEN", typeof(System.String)));
                    CustomerDataTable.Columns.Add(new DataColumn("Responsibility", typeof(System.String)));
                    CustomerDataTable.Columns.Add(new DataColumn("Affects", typeof(System.String)));
                    CustomerDataTable.Columns.Add(new DataColumn("ResponsibilityID", typeof(System.String)));
                    CustomerDataTable.Columns.Add(new DataColumn("AffectsID", typeof(System.String)));
                    CustomerDataTable.Columns.Add(new DataColumn("Remark", typeof(System.String)));
                    CustomerDataTable.Columns.Add(new DataColumn("IsExisted", typeof(System.String)));
                    Session[SessionFlag.CustomerSessionEZ] = CustomerDataTable;
                }
            }
            if (CustomerDataTable.Select("IsExisted='" + BEGDC.CC.BL.Common.CISFlag.NotExisted + "'").Length > 0)
            {
                this.Lb_CISWarning.Visible = true;
            }
            else
            {
                this.Lb_CISWarning.Visible = false;
            }
            this.dgCustomerList.DataSource = this.SetRowID(CustomerDataTable);
            this.dgCustomerList.DataBind();
        }

        private string BuildSelectedActivies()
        {
            string activies = string.Empty;
            foreach (ListItem li in this.chkListActivities.Items)
            {
                if (li.Selected)
                {
                    activies += li.Text + ";";
                }
            }
            return activies.Trim(';');
        }

        void ibtnSave_Click(object sender, EventArgs e)
        {
            try
            {
                //if (string.IsNullOrEmpty(this.ddlCATBranch.SelectedValue))
                //{
                //    this.ddlCATBranch.ControlStyle.BackColor = Color.Red;
                //    Page.RegisterClientScriptBlock("", "<script>alert('Please select a CAT or Branch!');</script>");
                //    return;
                //}

                IEV EVService = AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.EVService] as IEV;
                if (!this.BuildApp2Save()) return;

                System.Collections.IList list = new System.Collections.ArrayList();
                this.BuildALAttendee(ref list);

                IList custAttendeeList = new ArrayList();
                BuildCustomerAttendee(ref custAttendeeList);

                EVService.SaveEVRequest(this.Application, this.CustInfo, list, custAttendeeList, null);
                //Save ASB Leaders
                this.BuildASBLeaders(this.Application.Id);

                Session["AppID"] = this.Application.Id;
                this.ctrlExport.Visible = true;

                string url = Request.Form["tbURL"];
                string script = "<script>" + "alert('" + BEGDC.CC.Resource.SystemMessage.CV001 + "');";
                //				if(url == string.Empty)
                //					script += "VBAlert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');";
                script += "var scollvalue = $('input.positionflag').val();";
                if (url != string.Empty)
                {
                    if (url.IndexOf("AppID") == -1)
                        url = url.Substring(0, url.IndexOf("?") + 1) + "AppID=" + this.Application.Id + "&" + url.Substring(url.IndexOf("?") + 1);
                    script += "window.location.href='" + url + "'";
                }
                else
                {
                    url = Request.Url.AbsoluteUri;
                    if (url.IndexOf("AppID") == -1)
                        url = url.Substring(0, url.IndexOf("?") + 1) + "AppID=" + Application.Id + "&" + url.Substring(url.IndexOf("?") + 1);
                    script += "window.location.href='" + url + "'";
                }


                if (script.Contains("&pf="))
                {
                    script = script.Substring(0, script.IndexOf("&pf="));
                    script += "'+ '&pf=' + scollvalue";
                }
                else
                {
                    script += "+ '&pf=' + scollvalue";
                }

                script += "</script>";

                if (!Access.IsQuery)
                {
                    this.ibtnCopy.Visible = true;
                }

                this.AppID = this.Application.Id;

                Page.RegisterStartupScript("", script);



                //Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CV001 + "');</script>");
            }
            catch
            {
                Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CV002 + "');</script>");
            }
        }

        void ibtnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                IList attTypes = new ArrayList();
                attTypes.Add(BEGDC.CC.BL.CCFlow.AttachmentType.SUMMARY);
                attTypes.Add(BEGDC.CC.BL.CCFlow.AttachmentType.AGENDA);
                string msg = BEGDC.CC.BL.CCFlow.AttachmentService.GetMissedAttachmentMessage(this.AppID, attTypes);
                if (msg != "" && msg != string.Empty)
                {
                    Page.RegisterClientScriptBlock("", "<script>alert('" + msg + "')</script>");
                    return;
                }

                IEV evService = AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.EVService] as IEV;
                if (!this.BuildApp2Save()) return;

                BEGDC.CC.BL.UserManagement.IUser userService = AppContainer.Instance[ServiceConst.UserService] as BEGDC.CC.BL.UserManagement.IUser;
                Employee director = userService.GetUserByEnglishName(this.txtDirectorName.Value);
                //Employee applicant = userService.GetUserByEnglishName(this.lblApplicantValue.Text);
                Employee applicant = this.RequesterInfoControl.Employee;
                System.Collections.IList list = new System.Collections.ArrayList();
                this.BuildALAttendee(ref list);
                IList custAttendeeList = new ArrayList();
                BuildCustomerAttendee(ref custAttendeeList);

                if (custAttendeeList == null || custAttendeeList.Count == 0)
                {
                    Page.RegisterClientScriptBlock("", "<script>alert('At least one customer should be specified. 至少有一个客户参与!');</script>");
                    return;
                }

                evService.SubmitEVRequest(this.Application, this.CustInfo, list, custAttendeeList, applicant, director, this.FlowID, null);
                //Save ASB Leaders
                this.BuildASBLeaders(this.Application.Id);

                Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');window.close();</script>");
            }
            catch
            {
                Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CV002 + "');</script>");
            }
        }

        private void dtGridProExecutives_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
        {
            if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
            {
                try
                {
                    ImageButton Btn_Edit = (ImageButton)e.Item.Cells[3].FindControl("Btn_ALEdit");
                    string ItemId = e.Item.Cells[0].Text.ToString();
                    Btn_Edit.Attributes.Add("onclick", "OpenALAttendeePane('" + ItemId + "');");

                    ImageButton btnDel = (ImageButton)e.Item.Cells[3].FindControl("Btn_ALDelete");
                    btnDel.Attributes.Add("onclick", "return confirm('Are you sure to delete this item?')");
                    btnDel.Attributes.Add("check", "false");
                }
                catch (Exception ex)
                {
                    WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
                }
            }
        }



        private void dtGridProExecutives_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                string itemId = e.Item.Cells[0].Text;
                if (this.AlAttendee != null)
                {
                    try
                    {
                        DataTable table = (DataTable)this.AlAttendee;
                        DataRow[] rows = table.Select("Id =" + itemId);
                        table.Rows.Remove(rows[0]);
                        this.dtGridProExecutives.DataSource = table;
                        this.dtGridProExecutives.DataBind();
                        this.AlAttendee = table;
                    }
                    catch (Exception ex)
                    {
                        WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
                    }
                }
            }
        }

        private void btnSearch_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            if (this.txtCustomerID.Text != "")
            {
                IQuery queryService = AppContainer.Instance[ServiceConst.QueryService] as IQuery;
                CustomerInfo info = queryService.GetCustomerInfoById(Convert.ToInt32(txtCustomerID.Text));
                if (info != null)
                {
                    this.txtCompany.Text = info.Company;
                    this.txtVenue.Text = info.Venue;
                }
            }
        }


        void ibtnCopy_Click(object sender, EventArgs e)
        {
            try
            {
                IEV evService = AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.EVService] as IEV;

                evService.CopyEV(this.Application.Id);

                Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CM004 + "')</script>");

            }
            catch
            {
                Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CV002 + "');</script>");
            }

        }

        private void ibtnClose_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {

        }

        private void dgCustomerList_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
        {
            if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
            {
                ImageButton Btn_Edit = (ImageButton)e.Item.Cells[5].FindControl("Btn_Edit");
                string ItemId = e.Item.Cells[0].Text.ToString();
                Btn_Edit.Attributes.Add("onclick", "OpenCustomerPane('" + ItemId + "');");
                Btn_Edit.Attributes.Add("check", "false");

                ImageButton ld = (ImageButton)e.Item.Cells[6].FindControl("Btn_Delete");
                if (ld != null)
                {
                    ld.Attributes.Add("onclick", "return confirm('Are you sure to delete this item?');");
                    ld.Attributes.Add("check", "false");
                }

                string IsExisted = e.Item.Cells[7].Text.ToString();
                if (IsExisted == BEGDC.CC.BL.Common.CISFlag.NotExisted)
                {
                    System.Web.UI.WebControls.Image WarningImg = (System.Web.UI.WebControls.Image)e.Item.Cells[8].FindControl("CISWarning");
                    WarningImg.Visible = true;
                    WarningImg.ImageUrl = "../../images/Warning.gif";
                    WarningImg.ToolTip = "The Customer is not in CIS (该客户不是CIS成员)";
                }

                if (IsExisted == BEGDC.CC.BL.Common.CISFlag.Existed)
                {
                    System.Web.UI.WebControls.Image WarningImg = (System.Web.UI.WebControls.Image)e.Item.Cells[8].FindControl("CISWarning");
                    WarningImg.ImageUrl = "../../images/GreenWarningImg.gif";
                    WarningImg.ToolTip = "The Customer is in CIS (该客户是CIS成员)";
                    WarningImg.Visible = true;
                }
            }
        }

        private void dgCustomerList_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "Delete")
                {

                    int rowid = Convert.ToInt32(e.Item.Cells[0].Text);

                    DataTable customerAttendee = (DataTable)Session[SessionFlag.CustomerSessionEZ];
                    DataRow customerRow = customerAttendee.Rows[rowid - 1];
                    customerAttendee.Rows.Remove(customerRow);
                    this.BindCustomerAttendee();
                }
            }
            catch
            {
            }
        }

        private void ddlCATBranch_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            //this.ddlCATBranch.ControlStyle.BackColor = this.color;
            IQuery query = AppContainer.Instance[ServiceConst.QueryService] as IQuery;

            if (!string.IsNullOrEmpty(this.ddlCATBranch.SelectedValue))
            {
                this.lblCluster.Text = query.GetClusterByProvinceName(this.ddlCATBranch.SelectedValue.ToString());
                //ibtnSave_Click(this.ibtnSave, null);

                BEGDC.CC.Entity.Department dep = null;

                if (!string.IsNullOrEmpty(this.lblCluster.Text))
                    dep = query.GetDepartmentByPCAT(this.ddlCATBranch.SelectedValue, true);
                else
                    dep = query.GetDepartmentByPCAT(this.ddlCATBranch.SelectedValue, false);

                if (dep == null)
                {
                    Page.RegisterClientScriptBlock("", "<script>alert('No department in the PCAT. 该省份或大客户没有对应的部门!');</script>");
                    this.ddlCATBranch.SelectedIndex = 0;
                    this.lblCluster.Text = string.Empty;
                    //this.lblCluster.CssClass = "";
                }
                else
                {
                    if (dep != null && dep.DepartmentType.DicItemKey == "CAT")
                    {
                        //this.lblAccount.Visible = false;
                        this.ddlAccount.Visible = false;
                    }
                    else
                    {
                        //this.lblCluster.CssClass = "Cluster_Block";
                        // this.lblAccount.Visible = true;
                        this.ddlAccount.Visible = true;
                    }
                }
            }
            else
            {
                this.lblCluster.Text = "";
            }
        }

        void ibtnReply_Click(object sender, EventArgs e)
        {
            IEV evService = AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.EVService] as IEV;

            if (this.tbOperationFlag.Text == "reply")
            {
                //Save application info
                this.BuildApp2Save();
                System.Collections.IList list = new System.Collections.ArrayList();
                this.BuildALAttendee(ref list);

                IList custAttendeeList = new ArrayList();
                BuildCustomerAttendee(ref custAttendeeList);

                evService.SaveEVRequest(this.Application, this.CustInfo, list, custAttendeeList, null);

                evService.ReplyQuery(Convert.ToInt64(Request.QueryString["flowid"]), WebUtility.DeCodeString(Server, this.tbOperationContent.Text));
                Page.RegisterClientScriptBlock("", "<script>alert('Operate successfully!');window.close();</script>");
            }
        }

        private void BindASBLeaders()
        {
            //BEGDC.CC.BL.Common.Query.IQuery query = AppContainer.Instance[ServiceConst.QueryService] as BEGDC.CC.BL.Common.Query.IQuery;
            //DataTable table = this.btnProposedExecutives.Visible ? query.GetDicItemByTypeName(BEGDC.CC.BL.Common.DicType.ASBLeaders) : query.GetAppASBLeadersList(this.Application.Id);
            //this.CBL_ASBLeader.DataSource = table.DefaultView;
            //this.CBL_ASBLeader.DataValueField = "DicItemID";
            //this.CBL_ASBLeader.DataTextField = "DicItemKey";
            //this.CBL_ASBLeader.DataBind();

            //// Set the selected ASB Leaders
            //if (this.Application != null && this.Application.Id > 0)
            //{
            //    BEGDC.CC.BL.Common.IUtility utility = AppContainer.Instance[ServiceConst.UtilityService] as BEGDC.CC.BL.Common.IUtility;
            //    IList appASBLeadersList = utility.AppASBLeadersList(this.Application.Id);
            //    if (appASBLeadersList != null && appASBLeadersList.Count > 0)
            //    {
            //        System.Web.UI.WebControls.ListItem item = null;
            //        for (int i = 0; i < appASBLeadersList.Count; i++)
            //        {
            //            ASBCC.Database.EntityFramework.AppASBSenoirLeaders appASBLeaders = appASBLeadersList[i] as ASBCC.Database.EntityFramework.AppASBSenoirLeaders;

            //            if (appASBLeaders.ASBLeaders == null) continue;
            //            item = this.CBL_ASBLeader.Items.FindByValue(appASBLeaders.ASBLeaders.DicItemID.ToString());
            //            if (item != null) item.Selected = true;
            //        }
            //    }
            //}
            BEGDC.CC.BL.Common.Query.IQuery query = AppContainer.Instance[ServiceConst.QueryService] as BEGDC.CC.BL.Common.Query.IQuery;
            if (this.trCheckBoxASBLeader.Visible && !this.trDataGridASBLeader.Visible)
            {
                DataTable table = query.GetDicItemByTypeName(BEGDC.CC.BL.Common.DicType.ASBLeaders);
                this.CBL_ASBLeader.DataSource = table.DefaultView;
                this.CBL_ASBLeader.DataValueField = "DicItemID";
                this.CBL_ASBLeader.DataTextField = "NameChinese";
                this.CBL_ASBLeader.DataBind();
                // Set the selected ASB Leaders
                if (this.Application != null && this.Application.Id > 0)
                {
                    BEGDC.CC.BL.Common.IUtility utility = AppContainer.Instance[ServiceConst.UtilityService] as BEGDC.CC.BL.Common.IUtility;
                    IList appASBLeadersList = utility.AppASBLeadersList(this.Application.Id);
                    if (appASBLeadersList != null && appASBLeadersList.Count > 0)
                    {
                        System.Web.UI.WebControls.ListItem item = null;
                        for (int i = 0; i < appASBLeadersList.Count; i++)
                        {
                            ASBCC.Database.EntityFramework.AppASBSenoirLeaders appASBLeaders = appASBLeadersList[i] as ASBCC.Database.EntityFramework.AppASBSenoirLeaders;
                            if (appASBLeaders.ASBLeaders == null) continue;
                            item = this.CBL_ASBLeader.Items.FindByValue(appASBLeaders.ASBLeaders.DicItemID.ToString());
                            if (item != null) item.Selected = true;
                        }
                    }
                }
            }
            else
            {
                DataTable table2 = query.GetAppASBLeadersList2(this.Application.Id);
                this.dgASBLeaders.DataSource = table2;
                this.dgASBLeaders.DataBind();
            }
        }

        private void BuildASBLeaders(int appID)
        {
            if (appID > 0 && this.Application != null)
            {
                BEGDC.CC.BL.Common.IUtility utility = AppContainer.Instance[ServiceConst.UtilityService] as BEGDC.CC.BL.Common.IUtility;
                utility.DeleteAppASBSenoirLeadersByAppID(appID);
                int Count = this.CBL_ASBLeader.Items.Count;
                System.Web.UI.WebControls.ListItem item = null;
                for (int i = 0; i < Count; i++)
                {
                    item = this.CBL_ASBLeader.Items[i] as ListItem;
                    if (item.Selected)
                    {
                        utility.SaveASBLeaders(appID, int.Parse(item.Value));
                    }
                }
            }
        }
    }
}
